/**
 * Created with JetBrains WebStorm.
 * User: c-sailor.zhang
 * Date: 1/25/13
 * Time: 11:01 AM
 * To change this template use File | Settings | File Templates.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    crypto = require('crypto');

var UserSchema = new Schema({
    name:String,
    password:String,
    sex:Number,
    email:String,
    phone:String,
    address:String,
    token:String,
    shop:{ type:Schema.ObjectId,ref: 'Shop'},
	role:{ type:Number, default:0 }
});

UserSchema.pre('save', function(next) {
	var user = this;
	if (!user.isModified('password')) return next();
	user.password = encryptPassword(user.password);
	next();
});
UserSchema.method("authenticate", function (plainText) {
    if(!plainText) return false;
    return encryptPassword(plainText) === this.password;
});
UserSchema.static("baseInfo", function (uname) {
    return this.findOne({name:uname}).select('name role').exec();
});
function encryptPassword(password) {
    return crypto.createHash("md5").update(password).digest("base64");
}

mongoose.model('User', UserSchema);